/**
 * 
 */
package com.lanswon.qzsmk.util;

/**
 * @author sun
 *
 */
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.imageio.stream.FileImageInputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.junit.Test;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;

import com.lanswon.qzsmk.base.PathContants;
import com.lanswon.qzsmk.exception.ApplicationException;
import com.lanswon.qzsmk.exception.ErrorCode;
import com.lanswon.qzsmk.exception.SystemException;
import com.lanswon.qzsmk.vo.UploadFtpVo;

/**
 * ftp工具类
 */
public class FtpUtil {

	private static Logger logger = (Logger) LoggerFactory.getLogger(FtpUtil.class);

	@Test
	public void ff() throws Exception {
		System.out.println("1111");
		FTPClient ftp = new FTPClient();
		
		ftp.connect("192.168.89.37", 21);
		System.out.println("ssss");
		System.out.println(ftp.login("Administrator", "Lanswon@soft"));
		System.out.println(ftp.getReplyCode());
//		
	}

	/**
	 * 创建文件夹
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param pwd
	 * @param fileName
	 * @return
	 */
	public static boolean createFile(String url, int port, String username, String pwd, String path) {
		// 创建FTPClient对象
		boolean success = false;

		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(url, port);

			ftp.login(username, pwd);
			// 看返回的值是不是230，如果是，表示登陆成功
			int reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			success = ftp.changeWorkingDirectory(path);
			if (!success) {
				success = ftp.makeDirectory(path);
				ftp.changeWorkingDirectory(path);
			}
		} catch (SocketException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}

		return success;

	}

	/**
	 * 批量移动文件
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param pwd
	 * @return
	 */
	public static boolean moveBatchFile(String url, int port, String username, String pwd, Map<String, String> map) {
		// 创建FTPClient对象
		boolean success = false;

		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(url, port);

			ftp.login(username, pwd);
			// 看返回的值是不是230，如果是，表示登陆成功
			int reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			for (Entry<String, String> e : map.entrySet()) {
				String fromPath = e.getKey();
				String toPath = e.getValue();
				boolean b = ftp.changeWorkingDirectory(fromPath);
				if (!b) {
					ftp.makeDirectory(fromPath);
					ftp.changeWorkingDirectory(fromPath);
				}
				// 将上传文件存储到指定目录
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				ftp.rename(fromPath, toPath);
			}

			// 退出ftp
			ftp.logout();
			// 表示上传成功
			success = true;
		} catch (SocketException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * 单个移动文件
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param pwd
	 * @return
	 */
	public static boolean moveSingleFile(String url, int port, String username, String pwd, String fromPath,
			String toPath) {
		// 创建FTPClient对象
		boolean success = false;

		FTPClient ftp = new FTPClient();
		try {
			ftp.connect(url, port);

			ftp.login(username, pwd);
			// 看返回的值是不是230，如果是，表示登陆成功
			int reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			boolean b = ftp.changeWorkingDirectory(fromPath);
			if (!b) {
				ftp.makeDirectory(fromPath);
				ftp.changeWorkingDirectory(fromPath);
			}
			// 将上传文件存储到指定目录
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.rename(fromPath, toPath);
			// 退出ftp
			ftp.logout();
			// 表示上传成功
			success = true;
		} catch (SocketException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * 批量上传文件
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param path
	 * @param map
	 * @return
	 * @throws IOException 
	 */
	public static boolean uploadFile1(String url, int port, String username, String password, String path,
			Map<String, InputStream> map) throws IOException {
		// 初始表示上传失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
//		ftp.enterLocalPassiveMode();
		ftp.setControlEncoding("gb2312");
		
		ftp.setBufferSize(1024 * 1024 * 10 );
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			// 看返回的值是不是230，如果是，表示登陆成功
			reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			System.out.println(reply);
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			// 转到指定上传目录
			logger.debug("图片上传至路径【{}】", path);
			boolean b = ftp.changeWorkingDirectory(path);
			if (!b) {
				ftp.makeDirectory(path);
				ftp.changeWorkingDirectory(path);
			}
			// 将上传文件存储到指定目录
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			for (Entry<String, InputStream> e : map.entrySet()) {
				logger.debug("正在上传图片...【{}】", e.getKey());
				BufferedInputStream bis = new BufferedInputStream(e.getValue());
				ftp.storeFile(e.getKey(), bis);

				// 关闭输入流
				e.getValue().close();
				bis.close();
			}
			logger.debug("-----设置的缓冲区=--》》[{}]",ftp.getBufferSize());
			// 退出ftp
			ftp.logout();
			// 表示上传成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;

	}

	// 实验1
	public static boolean uploadFile_map(String url, int port, String username, String password, String path,
			Map<String, InputStream> map) {
		boolean success = false;
		FTPClient ftp = new FTPClient();// org.apache.commons.net.ftp
		try {
			if (port > -1) {
				ftp.connect(url, port);
			} else {
				ftp.connect(url);// ftp默认的端口是21
			}
			// 很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
			if (ftp.login(username, password)) {
				logger.debug("1111111111---path[{}]", path);
				ftp.enterLocalPassiveMode();
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 创建目录,如果存在会返回失败
				ftp.makeDirectory(path);
				// 切换目录
				ftp.changeWorkingDirectory(path);
				// 上传文件
				// FTP协议规定文件编码格式为ISO-8859-1
				logger.debug("222222");
				for (Entry<String, InputStream> e : map.entrySet()) {
					String filename = e.getKey();
					InputStream input = e.getValue();
					logger.debug("正在上传图片...【{}】，上传位置【{}】", filename, path + "/" + filename);

					filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
					logger.debug("aaaaaaaaa");
					OutputStream out = ftp.storeFileStream(filename);
					logger.debug("bbbbbbbb");
					byte[] byteArray = new byte[1024 * 1024 * 1024];
					logger.debug("ccccccc");
					int read = 0;
					logger.debug("dddd");
					while ((read = input.read(byteArray)) != -1) {
						logger.debug("*****");
						out.write(byteArray, 0, read);
					}
					logger.debug("3333333");
					out.close();
					input.close();
				}

				ftp.logout();
				logger.debug("44444");
			}
		} catch (Exception e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	// 实验2
	public static boolean uploadFile_stram_map(String url, int port, String username, String password, String path,
			Map<String, InputStream> map) {
		// 初始表示上传失败
		boolean success = false;
		FTPClient ftp = new FTPClient();// org.apache.commons.net.ftp
		try {
			if (port > -1) {
				logger.debug("------ftp正在连接------");
				ftp.connect(url, port);
			} else {
				ftp.connect(url);// ftp默认的端口是21
			}
			// 很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
			boolean cc = ftp.login(username, password);
			if (cc) {
				logger.debug("------ftp连接成功[{}]------",cc);
				
				logger.debug("------ftp设置被动模式------");
				ftp.enterLocalActiveMode();
				logger.debug("------ftp传输方式二进制------");
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 创建目录,如果存在会返回失败
				
				boolean v = ftp.makeDirectory(path);
				logger.debug("------ftp创建目录[{}]------",v);	
				
				// 切换目录
				logger.debug("------ftp切换目录【{}】------",path);
				ftp.changeWorkingDirectory(path);
				// 上传文件
				// FTP协议规定文件编码格式为ISO-8859-1
//				OutputStream out = null;
				logger.debug("------ftp准备上传------");
				for (Entry<String, InputStream> e : map.entrySet()) {
					String filename = new String(e.getKey().getBytes("GBK"), "ISO-8859-1");
					String filePath = path + "/" + filename;
					logger.debug("正在上传图片...【{}】，上传位置【{}】", filename, filePath);
					InputStream input = e.getValue();
					logger.debug("-------正在读取---------");
					OutputStream out = ftp.storeFileStream(filePath);
					if(out == null){
						logger.debug("-----------空指针异常啊 ---fuck--------");
					}
					logger.debug("-------读取完毕，准备输出---------");
					byte[] byteArray = new byte[1024 * 1024 * 1024];
					int read = 0;
					while ((read = input.read(byteArray)) != -1) {
						logger.debug("---------正在输出-----------------");
						out.write(byteArray, 0, read);
					}
					logger.debug("------输出完毕---------");
					// 关闭输入流
					logger.debug("-----关闭流----");
					input.close();
					// bis.close();
					if(out != null)
					out.close();
					
				}
				
				logger.debug("-----关闭流完成，调用completePendingCommand----");
				if(!ftp.completePendingCommand()){
				     ftp.logout();
				     ftp.disconnect();
				     System.err.println("文件传输失败。");
				     System.exit(1);
				 }
				logger.debug("-----全部完成，准备下一次的上传----");
				success = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					logger.debug("---------关闭ftp---------");
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				} 
			}
		}
		return success;
	}

	/**
	 * Description: 向FTP服务器上传文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param path
	 *            FTP服务器保存目录
	 * @param filename
	 *            上传到FTP服务器上的文件名
	 * @param input
	 *            输入流
	 * @return 成功返回true，否则返回false
	 * @throws IOException
	 * 
	 * 
	 */
	public static boolean uploadFile(String url, int port, String username, String password, String path,
			String filename, InputStream input) {
		boolean success = false;
		FTPClient ftp = new FTPClient();// org.apache.commons.net.ftp
		try {
			if (port > -1) {
				ftp.connect(url, port);
			} else {
				ftp.connect(url);// ftp默认的端口是21
			}
			// 很多人写的是用ftp.getReplyCode()给获取连接的返回值,但是这样会导致storeFileStream返回null
			logger.debug("准备连接ftp");
			if (ftp.login(username, password)) {
				logger.debug("连接ftp成功");
				ftp.enterLocalPassiveMode();
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 创建目录,如果存在会返回失败
				//ftp.makeDirectory(path);
				boolean f=ftp.changeWorkingDirectory(path);
				logger.debug("切换目录[{}]", path);
				logger.debug("切换目录[{}]", f);
				// 切换目录
				if(f){
					// 上传文件
					// FTP协议规定文件编码格式为ISO-8859-1
					logger.debug("正在上传...【{}】，上传位置【{}】", filename, path);
					filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
//					OutputStream out = ftp.storeFileStream(filename);
					f=ftp.storeFile(filename, input);
					logger.debug("上传文件执行storeFile（）=="+f);
					if(f){
						success = true;
					}					
				}
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			 String msg1="网络异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * Description: 从FTP服务器下载文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param startname
	 *            要下载的文件名起始名
	 * @param endname
	 *            要下载的文件名结束名
	 * @param localPath
	 *            下载后保存到本地的路径
	 * @return
	 * @throws IOException
	 */
	public static boolean downFile(String url, int port, String username, String password, String remotePath,
			String startname, String endname, String localPath) throws IOException {
		// 初始表示下载失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			} // 转到指定下载目录
				// ftp.setControlEncoding("gb2312");
				// ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.changeWorkingDirectory(remotePath);
			// 列出该目录下所有文件
			FTPFile[] fs = ftp.listFiles();
			// 遍历所有文件，找到指定的文件
			for (FTPFile ff : fs) {
				if (ff.getName().startsWith(startname) && ff.getName().endsWith(endname)) {
					// 根据绝对路径初始化文件
					File localFile = new File(localPath + "/" + ff.getName());
					// 输出流
					OutputStream is = new FileOutputStream(localFile);
					// 下载文件
					ftp.retrieveFile(ff.getName(), is);
					is.close();
					// 删除文件
					// ftp.deleteFile(ff.getName());
				}
			}
			// 退出ftp
			ftp.logout();
			// 下载成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	public static void deletAllFiles(FTPClient ftp, String remotePath) throws IOException {
		logger.debug("go in deletAllFiles");
		FTPFile[] listFiles1 = null;
		try {
			logger.debug("1111");
			listFiles1 = ftp.listFiles();
		} catch (IOException e1) {
			e1.printStackTrace();
			 String msg1="FTP异常";
				logger.error(msg1);
				throw new SystemException(SystemException.IOException, msg1);

		}
		logger.debug("22222");
		for (FTPFile file : listFiles1) {
			logger.debug("文件名【{}】", file.getName());
			// 是文件？
			if (file.isFile()) {
				try {
					ftp.deleteFile(file.getName());
				} catch (IOException e) {
					e.printStackTrace();
					String msg1="FTP异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
			// 是文件夹？
			else if (file.isDirectory() && !file.getName().startsWith(".")) {
				logger.debug("go in working directory[{}]", remotePath + File.separator + file.getName());
				// 接收文件夹目录下所有的文件实例
				FTPFile[] listFiles = null;
				try {
					ftp.changeWorkingDirectory(remotePath + File.separator + file.getName());
				} catch (IOException e1) {
					e1.printStackTrace();
					String msg1="FTP异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
				try {

					listFiles = ftp.listFiles();
				} catch (IOException e) {
					e.printStackTrace();
					String msg1="FTP异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);


				}
				// 文件夹为空 递归出口
				if (listFiles.length == 2 && listFiles[0].getName().startsWith(".")
						&& listFiles[1].getName().startsWith(".")) {
					logger.debug("空文件夹【{}】", file.getName());
					ftp.removeDirectory(file.getName());
				}
				for (FTPFile file2 : listFiles) {
					// foreach遍历删除文件 递归
					deletAllFiles(ftp, remotePath + File.separator + file.getName());
				}

				// 递归跳出来的时候删除空文件夹
				try {

					ftp.changeWorkingDirectory(remotePath);
					logger.debug("最后删除【{}】", file.getName());
					ftp.removeDirectory(file.getName());
				} catch (IOException e) {
					e.printStackTrace();
					String msg1="FTP异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);


				}
			}

		}

	}

	@Test
	public void TestDelete() {
		deleteAllFiles("192.168.0.12", 21, "zsw", "123456", "/resource/Enclosuresed");
	}

	/**
	 * 递归删除该文件夹下所有的文件及文件夹
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 *            该目录下
	 * @return
	 */
	public static boolean deleteAllFiles(String url, int port, String username, String password, String remotePath) {
		// 初始表示下载失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
		ftp.setControlEncoding("gb2312");
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			} // 转到指定下载目录
			ftp.changeWorkingDirectory(remotePath);

			logger.debug("start delete");
			deletAllFiles(ftp, remotePath);
			logger.debug("delete success");
			// 退出ftp
			ftp.logout();
			// 下载成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * 递归删除该文件夹,指定某写文件夹
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 *            该目录下
	 * @return
	 */
	public static boolean deleteAllFilesByApplyNOs(String url, int port, String username, String password,
			String remotePath, List<String> applyNos) {
		// 初始表示下载失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
		ftp.setControlEncoding("gb2312");
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			} // 转到指定下载目录
			logger.debug("start delete");
			for (String apply : applyNos) {
				String remotePath1 = remotePath + File.separator + apply;
				ftp.changeWorkingDirectory(remotePath1);
				deletAllFiles(ftp, remotePath1);
			}

			logger.debug("delete success");
			// 退出ftp
			ftp.logout();
			// 下载成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * Description: 从FTP服务器下载文件
	 * 
	 * @param url
	 *            FTP服务器hostname
	 * @param port
	 *            FTP服务器端口
	 * @param username
	 *            FTP登录账号
	 * @param password
	 *            FTP登录密码
	 * @param remotePath
	 *            FTP服务器上的相对路径
	 * @param startname
	 *            要下载的文件名起始名
	 * @param endname
	 *            要下载的文件名结束名
	 * @param localPath
	 *            下载后保存到本地的路径
	 * @return
	 */
	public static boolean deleteFile(String url, int port, String username, String password, String remotePath,
			String fileName) {
		// 初始表示下载失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
		ftp.setControlEncoding("gb2312");
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			} // 转到指定下载目录
			ftp.changeWorkingDirectory(remotePath);
			// 列出该目录下所有文件
			FTPFile[] fs = ftp.listFiles();
			// 遍历所有文件，找到指定的文件
			for (FTPFile ff : fs) {
				if (ff.getName().equals(fileName)) {
					// 删除文件
					ftp.deleteFile(ff.getName());
				}
			}
			// 退出ftp
			ftp.logout();
			// 下载成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * 批量删除文件
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @param fileName
	 * @return
	 */
	public static boolean deleteFile(String url, int port, String username, String password, String remotePath,
			List<String> fileNames) {
		// 初始表示下载失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
		ftp.setControlEncoding("gb2312");
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			reply = ftp.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			} // 转到指定下载目录
			ftp.changeWorkingDirectory(remotePath);
			// 列出该目录下所有文件
			FTPFile[] fs = ftp.listFiles();
			// 遍历所有文件，找到指定的文件
			for (FTPFile ff : fs) {
				for (String fileName : fileNames) {
					if (ff.getName().contains(fileName)) {
						// 删除文件
						ftp.deleteFile(ff.getName());
					}
				}

			}
			// 退出ftp
			ftp.logout();
			// 下载成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;
	}

	/**
	 * 获取指定远程目录下的文件list
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @return
	 * @throws ApplicationException 
	 */
	@SuppressWarnings("unchecked")
	public static List<FTPFile> getFileList(String url, int port, String username, String password, String remotePath) throws ApplicationException {
		List<FTPFile> list = new ArrayList<FTPFile>();
		FTPClient ftp = new FTPClient();		
		try {
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			if (port > -1) {
				ftp.connect(url, port);
			} else {
				ftp.connect(url);// ftp默认的端口是21
			}
			//ftp.enterLocalActiveMode();
			ftp.enterLocalPassiveMode();//被动模式
			// 登录ftp				
			if(ftp.login(username, password)){
				logger.debug("FTP login success"+PathContants.FTP_PATH_PHOTO);
				
				boolean b = ftp.changeWorkingDirectory(remotePath);
				if (!b) {
					throw new ApplicationException(ErrorCode.OTHER_EXCEPTION,"文件路径不存在");
				}
				logger.debug("remotePath={}",remotePath);
				logger.debug("ftp.changeWorkingDirectory()"+b);
				
				// 列出该目录下所有文件
				logger.debug("start   ftp.listFiles()");
				FTPFile[] fs = ftp.listFiles();
				for(FTPFile f:fs){
					if(f.isFile()){
						list.add(f);
					}
				}	
				// 退出ftp
				ftp.logout();
				// 下载成功
				
			}
					
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return list;
	}
	
	/**
	 * 获取远程指定文件流
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param remotePath
	 * @return
	 * @throws ApplicationException 
	 */
	public static InputStream getInputStream(String url, int port, String username, String password, String remotePath,String fileName) throws ApplicationException{
		InputStream inputStream = null;
//		List<FTPFile> list = new ArrayList<FTPFile>();
		FTPClient ftp = new FTPClient();		
		try {
			if (port > -1) {
				ftp.connect(url, port);
			} else {
				ftp.connect(url);// ftp默认的端口是21
			}
			// 登录ftp			
			if(ftp.login(username, password)){
				boolean b = ftp.changeWorkingDirectory(remotePath);
				logger.debug("文件路径"+remotePath);
				if (!b) {
					throw new ApplicationException(ErrorCode.OTHER_EXCEPTION,"文件路径不存在");
				}
				// 列出该目录下所有文件
				ftp.enterLocalPassiveMode();
				inputStream=ftp.retrieveFileStream(new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));			
				// 退出ftp
				ftp.logout();
				// 下载成功				
			}					
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					String msg1="FTP关闭异常";
					logger.error(msg1);
					throw new SystemException(SystemException.IOException, msg1);
				}
			}
		}
		return inputStream;
	}

	@Test
	public void testDownLoad() {
		try {
			boolean flag = downFile("10.1.28.7", 21, "testftp", "testftp", "/home/testftp/bank/CMB/acc", "WXSMK-QC-",
					".txt", "G:/");

			System.out.println(flag);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) throws ApplicationException {
//		List<FTPFile> l = getFileList("192.168.0.12", 21, "zsw", "123456", "/qzsmk/card/resource/makeCardFile/bank/WF_BANK/CNU");
//		List<FTPFile> l = getFileList("61.160.81.178", 18019, "ftpuser", "Lanswon@soft", "/qzsmk/balance/");
//		for(FTPFile f:l){
//			if(f.isFile()){				
//				System.out.println(f.getName());
//			}
//			
//		}
//		InputStream inputStream=getInputStream("192.168.0.12", 21, "zsw", "123456", "/qzsmk/card/resource/makeCardFile/bank/WF_BANK/CNU","CNU-WF1811140001.txt");
//		List<String>list = HttpUtil.getStreamString(inputStream);
//		for(String string:list){
//			System.out.println(string);
//		}
		System.out.println(System.getProperty("os.name"));
		System.out.println(System.getProperty("os.name").contains("Windows"));
	
	}

	/**
	 * Description：将本地文件上传到FTP服务器上
	 * 
	 * @throws IOException
	 */
	@Test
	public void testUpLoadFromDisk() throws IOException {
		try {
			logger.debug("开始");
			FileInputStream in = new FileInputStream(new File("D:/11_1_000089.xlsx"));
			boolean flag = uploadFile("192.168.0.12", 21, "zsw", "123456", "/qzsmk",
					"11_1_000089.xlsx", in);
			logger.debug("结束");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 移动文件
	 * 
	 * @throws IOException
	 */
	@Test
	public void testMove() throws IOException {
		try {
			FileInputStream in = new FileInputStream(new File("D:/80_1_smk008.xlsx"));
			boolean flag = moveSingleFile("192.168.0.12", 21, "zsw", "123456", "/resource/unexcels/80_1_smk001.xlsx",
					"/resource/excelsed/80_1_smk001/80_1_smk001.xlsx");
			System.out.println(flag);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Description：在FTP服务器上生成一个文件，并将一个字符串写入到该文件中
	 * 
	 * @throws IOException
	 */
	@Test
	public void testUpLoadFromString() throws IOException {
		try {
			InputStream input = new ByteArrayInputStream("test ftp".getBytes("utf-8"));
			boolean flag = uploadFile("10.1.28.7", 21, "testftp", "testftp", "/home/testftp/bank/CMB/acc", "test.txt",
					input);
			System.out.println(flag);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public static boolean upload_mini(String url, int port, String username, String password, String path,
			String filename, InputStream input) {
		boolean b = false;
		try {

			logger.debug("开始------");
			Long s = System.currentTimeMillis();
			FTPClient ftp = new FTPClient();
			ftp.connect(url, port);
			ftp.login(username, password);
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			ftp.changeWorkingDirectory(path);
			// BufferedInputStream input = new BufferedInputStream(new
			// FileInputStream(new
			// File("D://templmate/19_0_000095/460721199108135381.jpg")));
			filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
			OutputStream out = ftp.storeFileStream(filename);
			byte[] byteArray = new byte[1024 * 1024];
			int read = 0;
			while ((read = input.read(byteArray)) != -1) {
				out.write(byteArray, 0, read);
			}
			logger.debug("end---[{}]---", System.currentTimeMillis() - s);
			b = true;
		} catch (Exception e) {
			e.printStackTrace();
			b = false;
		}
		return b;
	}

	@Test
	public void gg() throws IOException {
		logger.debug("开始------");
		Long s = System.currentTimeMillis();
		FTPClient ftp = new FTPClient();
		ftp.connect("192.168.0.12", 21);
		ftp.login("zsw", "123456");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftp.changeWorkingDirectory("/resource/unbatchPhotos/19_0_000095");
		BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(
				"D://templmate/19_0_000095/aaa.rar")));
		String filename = new String("aaa.rar".getBytes("GBK"), "ISO-8859-1");
		OutputStream out = ftp.storeFileStream(filename);
		byte[] byteArray = new byte[1024 * 1024];
		int read = 0;
		while ((read = input.read(byteArray)) != -1) {
			out.write(byteArray, 0, read);
		}
		logger.debug("end---[{}]---", System.currentTimeMillis() - s);
	}

	@Test
	public void gg2() throws Exception {
		logger.debug("开始------");
		Long s = System.currentTimeMillis();
		FTPClient ftp = new FTPClient();
		ftp.connect("192.168.0.12", 21);
		ftp.login("zsw", "123456");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftp.changeWorkingDirectory("/resource/unbatchPhotos/19_0_000095");
		Map<String, InputStream> map = map();
		ftp.enterLocalPassiveMode();
		// ftp.setBufferSize(1024*1024);
		ftp.completePendingCommand();
		for (Entry<String, InputStream> e : map.entrySet()) {
			String filename = e.getKey();
			InputStream imput = e.getValue();
//			BufferedInputStream input = new BufferedInputStream(imput);
			// filename=new String(filename.getBytes("GBK"),"ISO-8859-1");
			OutputStream out = ftp.storeFileStream(filename);
			byte[] byteArray = new byte[1024 * 1024];
			int read = 0;
			while ((read = imput.read(byteArray)) != -1) {
				out.write(byteArray, 0, read);
			}
			out.close();
			imput.close();
//			input.close();
		}
		ftp.logout();

		logger.debug("end---[{}]---", System.currentTimeMillis() - s);
	}

	@Test
	public void g1g() throws IOException {
		logger.debug("开始------");
		Long s = System.currentTimeMillis();
		FTPClient ftp = new FTPClient();
		ftp.setBufferSize(1024 * 1024);
		ftp.connect("192.168.0.12", 21);
		ftp.login("zsw", "123456");
		ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
		ftp.setFileTransferMode(FTPClient.STREAM_TRANSFER_MODE);
		ftp.changeWorkingDirectory("/qzsmk/resource/unbatchPhotos/19_0_000095");
		BufferedInputStream input = new BufferedInputStream(new FileInputStream(new File(
				"D://templmate/19_0_000095/aaa.rar")));
		String filename = new String("aaa.rar".getBytes("GBK"), "ISO-8859-1");

		boolean out = ftp.storeFile(filename, input);

		logger.debug("end---[{}]---", System.currentTimeMillis() - s);
	}
	
	

	public static byte[] image2byte(String path) {
		byte[] data = null;
		FileImageInputStream input = null;
		try {
			input = new FileImageInputStream(new File(path));
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int numBytesRead = 0;
			while ((numBytesRead = input.read(buf)) != -1) {
				output.write(buf, 0, numBytesRead);
			}
			data = output.toByteArray();
			output.close();
			input.close();
		} catch (FileNotFoundException ex1) {
			ex1.printStackTrace();
			 String msg1="系统找不到文件异常";
				logger.error(msg1);
				throw new SystemException(SystemException.FileNotFoundException, msg1);

		} catch (IOException ex1) {
			ex1.printStackTrace();
			String msg1="IO流异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		}
		return data;
	}
	
	public static List<String> list() throws Exception {
		List<String> list = new ArrayList<>();
		String p = "D:\\templmate\\19_0_000095\\qqq";
		File f = new File(p);
		File[] ff = f.listFiles();
		if(ff.length == 0 ){
			return list;
		}
		for (File fff : ff) {
			System.out.println(fff.getName() + ":" + f.getAbsolutePath() + File.separator + fff.getName());
			list.add(f.getAbsolutePath() + File.separator + fff.getName());
		}
		return list;
	}

	public static Map<String, InputStream> map() throws Exception {
		Map<String, InputStream> map = new HashMap<>();
		File f = new File("D:\\templmate\\19_0_000095\\qqq");
		File[] ff = f.listFiles();
		if(ff.length == 0 ){
			return map;
		}
		for (File fff : ff) {
			System.out.println(fff.getName() + ":" + f.getAbsolutePath() + File.separator + fff.getName());
			map.put(fff.getName(), new FileInputStream(f.getAbsolutePath() + File.separator + fff.getName()));
		}
		return map;
	}
	
	/**
	 * 这个太慢了   一张照片要8s    api:  ftp.storeFile()
	 * @throws Exception
	 */
	@Test
	public void ff1() throws Exception{
		Map<String, InputStream> map = map();
		uploadFile1("192.168.0.12", 21, "zsw", "123456", "/resource/unbatchPhotos/19_0_000095", map);
	}
	
	
	@Test
	public void ff2() throws Exception{
		Map<String, InputStream> map = map();
		Long s = System.currentTimeMillis();
		boolean b = uploadFile_stram_map("192.168.0.12", 21, "zsw", "123456", "/resource/unbatchPhotos/19_0_000095", map);
			System.out.print(b);
			logger.debug("花费【{}】",System.currentTimeMillis()-s);
	}
	
	@Test
	public void ff3() throws Exception{
		Map<String, InputStream> map = map();
		Long s = System.currentTimeMillis();
		for(Entry<String, InputStream> e:map.entrySet()){
			boolean b = uploadFile("192.168.0.12", 21, "zsw", "123456", "/resource/unbatchPhotos/19_0_000095", e.getKey(), e.getValue());
			
			
		}
		logger.debug("花费【{}】",System.currentTimeMillis()-s);
	}
	
	
	/**
	 * 文件统一上传ftp
	 * 
	 * @param url
	 * @param port
	 * @param username
	 * @param password
	 * @param path
	 * @param map
	 * @return
	 * @throws IOException 
	 */
	public static boolean uploadFile_ftp(String url, int port, String username, String password, List<UploadFtpVo> list
			) throws IOException {
		// 初始表示上传失败
		boolean success = false;
		// 创建FTPClient对象
		FTPClient ftp = new FTPClient();
//		ftp.enterLocalPassiveMode();
		ftp.setControlEncoding("gb2312");
		
		ftp.setBufferSize(1024 * 1024 * 10 );
		try {
			int reply;
			// 连接FTP服务器
			// 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
			ftp.connect(url, port);
			// 登录ftp
			ftp.login(username, password);
			// 看返回的值是不是230，如果是，表示登陆成功
			reply = ftp.getReplyCode();
			// 以2开头的返回值就会为真
			System.out.println(reply);
			
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
				return success;
			}
			
			// 将上传文件存储到指定目录
			ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
			
			for(UploadFtpVo vo :list){
				// 转到指定上传目录
				logger.debug("图片上传至路径【{}】", vo.getPath());
					ftp.makeDirectory(vo.getPath());
					ftp.changeWorkingDirectory(vo.getPath());
					
					Map<String, InputStream> map = vo.getMap();
					for (Entry<String, InputStream> e : map.entrySet()) {
						logger.debug("正在上传图片...【{}】", e.getKey());
						BufferedInputStream bis = new BufferedInputStream(e.getValue());
						ftp.storeFile(e.getKey(), bis);

						// 关闭输入流
						e.getValue().close();
						bis.close();
					}
					
			}
			
			logger.debug("-----设置的缓冲区=--》》[{}]",ftp.getBufferSize());
			// 退出ftp
			ftp.logout();
			// 表示上传成功
			success = true;
		} catch (IOException e) {
			e.printStackTrace();
			String msg1="FTP异常";
			logger.error(msg1);
			throw new SystemException(SystemException.IOException, msg1);

		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException ioe) {
					ioe.printStackTrace();
					 String msg1="FTP关闭异常";
						logger.error(msg1);
						throw new SystemException(SystemException.IOException, msg1);

				}
			}
		}
		return success;

	}
	
	@Test
	public void sad() throws FileNotFoundException{
		
		uploadFile("222.132.48.116", 21, "card", "123456", "/JS_BANK"+PathContants.separator+"CN", "dd.txt",new FileInputStream("D://dd.txt"));
	}

}
